package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:墨琦
 * Data:2023-09-06
 * Time:14:50
 */
//回显服务器
public class UdpEchoServer {
    private DatagramSocket socket=null;
    public  UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true)
        {
            //读取请求，并响应
            DatagramPacket request=new DatagramPacket(new byte[1024],1023);
            socket.receive(request);
                                    //获取数据报的信息
            String str=new String(request.getData(),0,request.getLength());
            //根据请求，计算出响应
                String str2=process(str);
            //返回客户端                                     //字节          字节长度                   ip和端口
            DatagramPacket response=new DatagramPacket(str2.getBytes(),str2.getBytes().length,request.getSocketAddress());
            socket.send(response);
                                                            //获取IP地址                    接口       获取数据报信息   获取回应数据
            System.out.printf("[%s:%d] rep:%s,resp: %s",request.getAddress().toString(),request.getPort(),str,str2);
        }
    }

    public String process(String str)
    {
        return "返回响应："+str;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoServer t1=new UdpEchoServer(9090);
        t1.start();
    }



}
